#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:Charmander

import json
import traceback

import requests

from Advisement_player import readConfig as readConfig
from Advisement_player.common.log import MyLog as Log

localReadConfig = readConfig.ReadConfig()

class ConfigHttp:

    def __init__(self):
        global scheme,timeout,host,port
        scheme = localReadConfig.get_http('scheme')
        host = localReadConfig.get_http('base_url')
        timeout = localReadConfig.get_http('timeout')
        port = localReadConfig.get_http('port')

        self.log = Log.get_log()
        self.logger = self.log.get_logger()
        self.headers = {}
        self.data = {}
        self.url = None
        self.files = {}
        self.state = 0

    def set_url(self,url):
        self.url = scheme +'://'+ host + url

    def set_headers(self,headers):
        self.headers = headers

    def set_data(self,body):
        self.data = body

    def set_files(self,filename):
        if filename != '':
            file_path = 'E:/Advisement_player/testFile/' + filename
            self.files = {'file':open(file_path,'rb')}

        if filename == '' or filename is None:
            self.state = 1

    def post(self):
        if self.headers != None:
            r = requests.post(url =self.url,data  =json.dumps(self.data),headers = self.headers,timeout =float(timeout))
        else:
            r = requests.post(url =self.url,data = json.dumps(self.data),timeout = 30)
        try:
            if r.status_code == 200:
                return r
            else:
                #对于http返回非200的code，输出相应的code
                raise Exception("http error info:%s" %r.status_code)
        except:
            if TimeoutError:
                self.logger.error('Time out')
            else:
                self.logger.error(traceback.print_exc())

    def get(self):
        if self.headers != None:
            r = requests.get(url =self.url,data = json.dumps(self.data),headers = self.headers,timeout = 30,verify=False)
        else:
            r = requests.get(url =self.url,data = json.dumps(self.data),timeout = 30,verify=False)
        try:
            if r.status_code == 200:
                return r
            else:
                #对于http返回非200的code，输出相应的code
                raise Exception("http error info:%s" %r.status_code)
        except:
            if TimeoutError:
                self.logger.error('Time out')
            else:
                self.logger.error(traceback.print_exc())

if __name__ == '__main__':
    print('ConfigHTTP')